<template>
<div>
  <div>
    <h2>员工管理</h2>
    <p>欢迎您: {{username}}</p>
  </div>
  <div>
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="员工名称:">
        <el-input v-model="ename" placeholder="请输入员工名称"></el-input>
      </el-form-item>
      <el-form-item label="部门:">
        <el-select v-model="did" placeholder="请选择部门">
          <el-option label="请选择" value=""></el-option>
          <el-option v-for="d in dlist" :label="d.departmentName" :value="d.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click.prevent="search">查询</el-button>
      </el-form-item>
      <el-button icon="el-icon-circle-plus" circle type="success"
                 size="medium"
                 @click="add">添加员工</el-button>
      <el-button icon="el-icon-remove" circle type="danger"
                 size="medium"
                 @click="delAll">批量删除</el-button>
    </el-form>
  </div>
  <div>
    <el-table
        :data="elist"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
          >
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          prop="id"
          label="ID"
          width="60">
      </el-table-column>
      <el-table-column
          prop="lastName"
          label="员工姓名"
          width="180">
      </el-table-column>
      <el-table-column
          label="头像"
          width="180">
        <template slot-scope="scope">
          <img :src="'http://localhost:81/emp60/'+scope.row.empImg" style="width: 60px;height: 60px;border-radius: 50%">
        </template>
      </el-table-column>
      <el-table-column
          prop="email"
          label="邮箱"
          width="180">
      </el-table-column>
      <el-table-column
          label="性别"
          width="100">
        <template slot-scope="scope">
          <span v-text="scope.row.gender==1?'男':'女'"></span>
        </template>
      </el-table-column>
      <el-table-column
          prop="birth"
          label="生日"
          width="180">
      </el-table-column>
      <el-table-column
          prop="departmentName"
          label="部门"
          width="180">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button icon="el-icon-edit" circle type="primary"
                     size="mini"
                     @click="edit(scope.row.id)"></el-button>
            <el-button icon="el-icon-delete" circle
                       size="mini"
                       type="danger"
                       @click="del(scope.row.id)" slot="reference"></el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!--添加页面-->
  <el-dialog title="添加员工" :visible.sync="addEmpDialogFormVisible" :close-on-click-modal="false">
    <el-form ref="addEmpForm" :model="addEmpRuleForm" :rules="addEmpRules" label-width="80px">
      <el-form-item label="用户名称" prop="lastName">
        <el-input v-model="addEmpRuleForm.lastName"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="addEmpRuleForm.email"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="addEmpRuleForm.gender">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="0">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="生日" prop="birth">
        <el-date-picker
            v-model="addEmpRuleForm.birth"
            type="date"
            placeholder="选择日期"
            :editable="false"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="部门:" prop="did">
        <el-select v-model="addEmpRuleForm.did" placeholder="请选择部门">
          <el-option label="请选择" value=""></el-option>
          <el-option v-for="d in dlist" :label="d.departmentName" :value="d.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="头像:" prop="empImg">
        <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
             name="uploadImg">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click.prevent="sure">确认</el-button>
        <el-button @click.prevent="resetAdd">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!--修改页面-->
  <el-dialog title="修改员工" :visible.sync="editEmpDialogFormVisible" :close-on-click-modal="false">
    <el-form ref="editEmpForm" :model="editEmpRuleForm" :rules="addEmpRules" label-width="80px">
      <el-form-item label="用户ID" prop="id">
        <el-input v-model="editEmpRuleForm.id" disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="用户名称" prop="lastName">
        <el-input v-model="editEmpRuleForm.lastName"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="editEmpRuleForm.email"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="editEmpRuleForm.gender">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="0">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="生日" prop="birth">
        <el-date-picker
            v-model="editEmpRuleForm.birth"
            type="date"
            placeholder="选择日期"
            :editable="false"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="部门:" prop="did">
        <el-select v-model="editEmpRuleForm.did" placeholder="请选择部门">
          <el-option label="请选择" value=""></el-option>
          <el-option v-for="d in dlist" :label="d.departmentName" :value="d.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="头像:" prop="empImg">
        <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            name="uploadImg">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click.prevent="save">确认</el-button>
        <el-button @click.prevent="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <div>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNow"
        :page-sizes="[3, 6, 12, 24]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
  </div>
</div>
</template>

<script>
export default {
  name: "Emp",
  data() {
    return {
      imageUrl:'',
      uploadUrl:'http://localhost:9009/myemp/emp/uploadImg',
      elist: [],
      dlist:[],
      ename:'',
      pageNow:1,
      pageSize:3,
      did:'',
      pages:0,
      total:0,
      prePage:0,
      nextPage:0,
      username:'',
      eid:[],
      addEmpDialogFormVisible: false,
      editEmpDialogFormVisible:false,
      addEmpRuleForm: {
        lastName: '',
        email: '',
        gender: '',
        birth: '',
        did: '',
        empImg:''
      },
      editEmpRuleForm: {
        id:'',
        lastName: '',
        email: '',
        gender: '',
        birth: '',
        did: '',
        empImg:''
      },
      addEmpRules: {
        lastName: [
          {required: true, message: '请输入员工名称', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入员工邮箱', trigger: 'blur'},
          {pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/, message: '请输入有效的邮箱格式', trigger: 'blur'}
        ],
        gender: [
          {required: true, message: '请输入员工性别', trigger: 'change'}
        ],
        birth: [
          {required: true, message: '请输入员工薪资', trigger: 'change'}
        ],
        did: [
          {required: true, message: '请输入员工部门', trigger: 'change'}
        ]
      },
      editEmpRules: {
        lastName: [
          {required: true, message: '请输入员工名称', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入员工邮箱', trigger: 'blur'},
          {pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/, message: '请输入有效的邮箱格式', trigger: 'blur'}
        ],
        gender: [
          {required: true, message: '请输入员工性别', trigger: 'change'}
        ],
        birth: [
          {required: true, message: '请输入员工薪资', trigger: 'change'}
        ],
        did: [
          {required: true, message: '请输入员工部门', trigger: 'change'}
        ]
      }
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.addEmpRuleForm.empImg=res.data;
      this.editEmpRuleForm.empImg=res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    delAll(){
      if (this.eid.length > 0){
        this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let url = "/emp/delBatch" ;
          let json = {'eid':this.eid} ;
          let parmas = this.$qs.stringify(json,{indices:false}) ;
          this.$axios({
            url:url,
            method:'delete',
            data:parmas, //eid=2&eid=4&eid=12
            headers: {'content-type':'application/x-www-form-urlencoded'}
          }).then(res=>{
            if (res.data.code == 200){
              this.$message({
                type: 'success',
                message: res.data.msg,
                duration:1000
              });
              this.initEmp() ;
            }else {
              this.$message({
                type:'error',
                message:res.data.msg,
                duration:1000
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }else {
        this.$message({
          type: 'info',
          message: '请至少选中一个员工!',
          dutation:1000
        });
      }
    },
    handleSelectionChange(checks){
      this.eid=[];
      if(checks.length>0){
        for(let c of checks){
          this.eid.push(c.id);
        }
      }
    },
    handleSizeChange(val){
      //val    就是选择每页多少条
      this.pageSize=val;
      this.pageNow=1;
      this.initEmp();
    },
    handleCurrentChange(val){
      //val 就是当前页
      this.pageNow=val;
      this.initEmp();
    },
    add() {
      this.addEmpDialogFormVisible = true;
    },
    del(id) {
      this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = '/emp/del/'+id;
        this.$axios.delete(url)
            .then((res)=>{
              if (res.data.code == 200){
                this.$message({
                  type: 'success',
                  message: res.data.msg,
                  duration:1000
                });
                this.initEmp();
              }else {
                this.$message({
                  message: res.data.msg,
                  type: 'error',
                  duration:1000
                });
              }
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    edit(id) {
      let url = '/emp/queryEmpBykey/'+id;
      this.$axios.get(url)
          .then((res)=>{
            if (res.data.code == 200){
              this.editEmpRuleForm=res.data.data;
              this.editEmpDialogFormVisible = true;
            }else {
              this.$message({
                message: res.data.msg,
                type: 'error',
                duration:1000
              });
            }
          })

    },
    resetAdd() {
      let form = this.$refs.addEmpForm;
      form.resetFields();
    },
    reset(){
      let form = this.$refs.editEmpForm;
      form.resetFields();
    },
    save(){
      let form = this.$refs.editEmpForm;
      form.validate((valid) => {
        if (!valid) {
          return;
        } else {
          let url = "/emp/modify";
          this.$axios.put(url,this.editEmpRuleForm).then((res)=>{
            //res  就是服务器端回应的数据 result
            console.log(res)
            if (res.data.code == 200){
              this.editEmpDialogFormVisible=false;
              this.imageUrl='';
              this.initEmp();
            }else {
              this.$message({
                message: res.data.msg,
                type: 'error',
                duration:1000
              });
            }
          })
        }
      })
    },
    sure() {
      let form = this.$refs.addEmpForm;
      form.validate((valid) => {
        if (!valid) {
          return;
        } else {
          let url = "/emp/add";
          this.$axios.post(url,this.addEmpRuleForm).then((res)=>{
            //res  就是服务器端回应的数据 result
            console.log(res)
            if (res.data.code == 200){
              this.addEmpDialogFormVisible=false;
              this.imageUrl='';
              this.resetAdd();
              this.initEmp();
            }else {
              this.$message({
                message: res.data.msg,
                type: 'error',
                duration:1000
              });
            }
          })
        }
      })
    },
    search(){
      this.pageNow=1;
      this.initEmp();
    },
    initEmp(){
      //在这个函数 中 给 plist 赋值
      let url = '/emp/list' ;
      this.$axios.get(url,{
        params:{ //键值对传参
          now:this.pageNow,
          size:this.pageSize,
          ename:this.ename,
          did:this.did
        }
      }).then((res)=>{
        if (res.data.code == 200) {
          this.elist = res.data.data.list;
          this.pageNow = res.data.data.pageNum;
          this.pageSize = res.data.data.pageSize;
          this.pages = res.data.data.pages;
          this.total = res.data.data.total;
          this.prePage = res.data.data.prePage;
          this.nextPage = res.data.data.nextPage;
        }else {
          this.$message({
            message: res.data.msg,
            type: 'error',
            duration:1000
          });
        }
      })
    },
    initDept(){
      //在这个函数 中 给 plist 赋值
      let url = '/dept/list' ;
      this.$axios.get(url).then((res)=>{
        if (res.data.code == 200) {
          this.dlist = res.data.data;
        }else {
          this.$message({
            message: res.data.msg,
            type: 'error',
            duration:1000
          });
        }
      })
    },
    initUser(){
      let strUser= sessionStorage.getItem("userInfo");
      let user = JSON.parse(strUser);
      this.username=user.username;
    }
  },
  created(){
    this.initDept();
    this.initEmp();
    this.initUser();
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style scoped>

</style>